const path = require('path')
// 打包体积分析
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const autoprefixer = require('autoprefixer');
const AddAssetHtmlCdnWebpackPlugin = require('add-asset-html-cdn-webpack-plugin');


// const pxtorem = require('postcss-pxtorem');
const pxtoviewport = require('postcss-px-to-viewport');

function resolve(dir) {
	return path.join(__dirname, './', dir)
}

// 预渲染
const PrerenderSPAPlugin = require('prerender-spa-plugin')
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

const cdnConfig = {
	vue: 'https://cdn.bootcss.com/vue/2.6.10/vue.min.js',
	vuex: 'https://cdn.bootcss.com/vuex/3.1.1/vuex.min.js',
	'vue-router': 'https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js'
}


// 第三方的模块
const externals = {
	vue: 'Vue',
	'vue-router': 'VueRouter',
	vuex: 'Vuex',
}
console.log(process.env.VUE_APP_BASE_SERVICE_API);
// 执行 vue inspect > output.js将下面的配置输出为webpack的配置文件重定向到一个文件以便进行查阅
module.exports = {
	outputDir: 'docs',
	publicPath: process.env.BASE_URL || './',
	productionSourceMap: false, // 生产环境下打开sourceMap，辅助定位错误位置
	// webpack内部配置，是webpack原始配置的上层抽象，可以定义具名loader规则和具名插件
	chainWebpack: config => {
		// 这里是对环境的配置，不同环境对应不同的BASE_URL，以便axios的请求地址不同
		// config.plugin('define').tap(args => {
		// 	args[0]['process.env'].BASE_URL = JSON.stringify(process.env.BASE_URL)
		// 	return args
		// })

		// set svg-sprite-loader
		config.module
			.rule('svg')
			.exclude.add(resolve('src/icons'))
			.end()
		config.module
			.rule('icons')
			.test(/\.svg$/)
			.include.add(resolve('src/icons'))
			.end()
			.use('svg-sprite-loader')
			.loader('svg-sprite-loader')
			.options({
				symbolId: 'icon-[name]'
			})
			.end()

		// 添加别名
		config.resolve.alias
			.set('@', resolve('src'))
			.set('assets', resolve('src/assets'))
			.set('style', resolve('src/style'))
			.set('api', resolve('src/api'))
			.set('mock', resolve('src/mock'))
			.set('util', resolve('src/util'))
			.set('router', resolve('src/router'))
			.set('components', resolve('src/components'))

		// 切分块
		config.optimization.splitChunks({
			chunks: 'all', // initial/async和all
			minSize: 30000, // 形成一个新代码块最小的体积
			maxAsyncRequests: 5, // 按需加载时最大的并行请求数
			maxInitialRequests: 3, // 最大初始化请求数
			automaticNameDelimiter: '~', // 打包分隔符
			name: true,
			cacheGroups: {
				vueBase: {
					name: 'vueBase',
					test: (module) => {
						return /vue/.test(module.context);
					},
					chunks: 'initial',
					priority: 10
				},
				vendor: {
					name: 'vendor',
					test: /[\\/]node_modules[\\/]/, // 打包第三方库
					chunks: "all",
					priority: 9 // 优秀级
				},
				common: { // 打包其余的公共代码
					minChunks: 2, // 引入两次及以上被打包
					name: "common", // 分离包的名字
					chunks: "all",
					priority: 5
				}
			}
		});
		// 生产环境下
		if (process.env.NODE_ENV === 'production') {
			// 分离第三方的包
			config.externals(externals)
			// 压缩代码
			config.optimization.minimize(true);
		}

		// 打包分析
		if (process.env.NODE_ENV == 'analyz') {
			config.plugin('webpack-report').use(BundleAnalyzerPlugin, [{
				analyzerMode: 'static'
			}])
		}

	},
	// webpack 简单/基础配置，比如引入一个新插件，该对象将会被 webpack-merge 合并入最终的 webpack 配置

	configureWebpack: (config) => {


		if (process.env.NODE_ENV === 'production') {
			return {
				plugins: [
					// 预渲染
					// new PrerenderSPAPlugin({
					// 	staticDir: resolve('dist'),
					// 	routes: ['/index', ], // 你需要预渲染的路由
					// 	renderer: new Renderer({
					// 		inject: {
					// 			_m: 'prerender'
					// 		},
					// 		// 渲染时显示浏览器窗口，调试时有用
					// 		headless: false,
					// 		// 等待触发目标时间后，开始预渲染
					// 		renderAfterDocumentEvent: 'render-event'
					// 	})
					// }),
					new AddAssetHtmlCdnWebpackPlugin(true, cdnConfig)
				]
			}
		}
	},
	// 让骨架屏的css分离，直接作为内联style处理到html中，提高载入速度
	css: {
		extract: true,
		sourceMap: false,
		modules: false,
		loaderOptions: {
			postcss: {
				plugins: [
					autoprefixer(),
					pxtoviewport({
						viewportWidth: 750,
						viewportUnit: 'vw',
						unitPrecision: 3,
						isSavePx: false,
						selectorBlackList: ['.ignore', '.hairlines', 'van'],
					})
				]
			},
			less: {
				modifyVars: {
					'hack': `true; @import "${resolve('./src/style/hack.less')}";`
				}
			}
		}
	},
	pluginOptions: {
		'style-resources-loader': {
			preProcessor: 'less',
			patterns: [resolve('src/style/var.less')]
		}
	},
	devServer: {
		open: true,
		proxy: {
			[process.env.VUE_APP_BASE_SERVICE_API]: {
				target: 'https://11learned.com', // target host
				secure: true, // 如果是https接口需要配置
				changeOrigin: true, // needed for virtual hosted sites
				pathRewrite: {
					['^' + process.env.VUE_APP_BASE_SERVICE_API]: `${process.env.VUE_APP_BASE_SERVICE_API}` // rewrite path
				}
			},
		}
	},

}
